package com.qf.dao.impl;

import com.qf.dao.CartDao;
import com.qf.domain.Cart;
import com.qf.domain.Goods;
import com.qf.utils.DataSourceUtils;
import com.qf.utils.TxUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author YDW
 * projectName:shopping
 * time:2022/4/19 22:19
 * description:
 */
public class CartDaoImpl implements CartDao {
    QueryRunner queryRunner=new QueryRunner(DataSourceUtils.getDataSource());
    @Override
    public Cart findByUidAndGid(int uid, int pid) {
        String sql=" select id,pid,num,money from tb_cart where id=? and pid=? ";
        try {
            Cart cart=queryRunner.query(sql, new BeanHandler<>(Cart.class),uid,pid);
            return cart;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void insert(Cart cart) {
        String sql=" insert  into tb_cart (id,pid,Num,money) values (?,?,?,?) ";
        try {
             queryRunner.update(sql,cart.getId(),cart.getPid(),cart.getNum(),cart.getMoney());

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateCart(Cart cart) {
        String sql=" update tb_cart set num=?,money=? where id=? and pid=?  ";
        try {
            queryRunner.update(sql,cart.getNum(),cart.getMoney(),cart.getId(),cart.getPid());

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Cart> findCartByUid(int uid) {
        String sql=" select id,pid,num,money from tb_cart where id=?";
        try {
            List<Cart> carts=queryRunner.query(sql, new BeanListHandler<>(Cart.class),uid);
            return carts;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void deleteCart(int uid, int pid) {
        String sql=" delete from tb_cart where id=? and pid=? ";
        try {
            queryRunner.update(sql,uid,pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void clearCartByUid(int uid) {
        Connection conn = TxUtils.getConn();
        QueryRunner qr=new QueryRunner();
        String sql=" delete from tb_cart where id=? ";
        try {
            qr.update(conn,sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
